package com.mediacloud.app.newsmodule.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.flyco.tablayout.SlidingTabLayout
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.assembly.adapter.CatalogContentFragmentAdapter
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.views.CornerBlurView
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.fragment.INaviateState
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.audio.live.AudioLiveColumnHomeIntroFragment
import com.mediacloud.app.newsmodule.fragment.audio.live.AudioLiveColumnHomeProgrammeListFragment
import com.mediacloud.app.newsmodule.fragment.audio.live.AudioLiveColumnHomeRecommendListFragment
import com.mediacloud.app.newsmodule.utils.*
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.share.utils.ShareGridDataUtil
import com.mediacloud.app.share.view.SharePopGridWindow
import com.mediacloud.app.user.utils.RxUtils
import com.mediacloud.app.util.ClickUtils
import com.mediacloud.app.util.DataUtils
import com.utils.DisplayUtil
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_area_live_list.*
import kotlinx.android.synthetic.main.activity_program_home.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * 广播  栏目   主页
 */
class AudioLiveColumnHomeActivity : BaseBackActivity(), View.OnClickListener, IChangeProgram {
    private var view_titlebar_bg: View? = null
    private var toolbar: Toolbar? = null
    private var tv_top_title: TextView? = null
    private var iv_back: ImageView? = null
    private var iv_share: ImageView? = null
    private var iv_top_bg: ImageView? = null
    private var iv_logo: CornerBlurView? = null
    private var tv_title: TextView? = null

    private var appBarLayout: AppBarLayout? = null
    private var collapsingToolbarLayout: CollapsingToolbarLayout? = null
    private var slidingTabLayout: SlidingTabLayout? = null
    private var viewPager: ViewPager? = null
    private var mAdapter: CatalogContentFragmentAdapter? = null
    private val mTitles: ArrayList<String> = ArrayList()
    private val mFragments: ArrayList<Fragment> = ArrayList<Fragment>()
    private var mCurrentPosition = 0
    private var mTitleStr: String? = null
    private var programArticleItem: ArticleItem? = null
    private var programCatalogItem: CatalogItem? = null
    private var shareWrap:ShareWrap?= null

//    var shareGridDataUtil: ShareGridDataUtil? = null
//    var sharePopGridWindow: SharePopGridWindow? = null
    companion object {
        @JvmStatic
        fun startActivity(context: Context?, articleItem: ArticleItem?, catalogItem: CatalogItem? = null) {
            if (context == null) {
                return
            }
            val intent = Intent(context, AudioLiveColumnHomeActivity::class.java)
            intent.putExtra("title", articleItem?.title)
            intent.putExtra("data", articleItem)
            intent.putExtra("catalogItem", catalogItem)
            context.startActivity(intent)
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_program_home
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initData(savedInstanceState)
        initListener()

    }

    fun initView() {
        view_titlebar_bg = findViewById(R.id.view_titlebar_bg)
        toolbar = findViewById(R.id.titleLayout)
        tv_top_title = findViewById(R.id.tv_top_title)
        iv_back = findViewById(R.id.iv_back)
        iv_share = findViewById(R.id.iv_share)
        iv_logo= findViewById(R.id.iv_logo)
        tv_title= findViewById(R.id.tv_title)

        iv_top_bg = findViewById(R.id.iv_top_bg)
        appBarLayout = findViewById(R.id.appBarLayout)
        collapsingToolbarLayout = findViewById(R.id.collapsingToolbarLayout)

        slidingTabLayout = findViewById(R.id.slidingTabLayout)
        viewPager = findViewById(R.id.viewPager)
    }

    private fun initData(savedInstanceState: Bundle?) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt("currentTabPosition", 0)
        }
        mTitleStr = intent.getStringExtra("title")
        programArticleItem = intent.getParcelableExtra("data")
        programCatalogItem = intent.getParcelableExtra("catalogItem")

        initShare()

        val statusBarHeight = StatusBarUtil.getStatusBarHeight(this)
        val toolbarBg = view_titlebar_bg?.layoutParams as ConstraintLayout.LayoutParams
        toolbarBg.height = DisplayUtil.dip2px(this, 42f) + statusBarHeight
        view_titlebar_bg?.layoutParams = toolbarBg
        changeProgramToUpdateUI(intent.getParcelableExtra("data"))
    }

    override fun changeProgramToUpdateUI(articleItem: ArticleItem?) {
        programArticleItem = articleItem
        tv_top_title?.text = programArticleItem?.title
        iv_logo?.load(programArticleItem?.logo, DisplayUtil.dip2px(this, 10f))
        tv_title?.text = programArticleItem?.title
        initFragment()
        getNewsDetail()
    }

    private fun initListener() {
        iv_back?.setOnClickListener(this)
        iv_share?.setOnClickListener(this)

        val yOff = intArrayOf(0)
        collapsingToolbarLayout?.post {
            appBarLayout?.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
                if (yOff[0] <= 0) {
                    if (collapsingToolbarLayout != null && toolbar != null) {
                        yOff[0] =
                                collapsingToolbarLayout!!.measuredHeight - toolbar!!.height
                    }
                }
                if (Math.abs(verticalOffset) >= yOff[0]) {
//                    Log.w(
//                            "APPTAG",
//                            "verticalOffset:" + verticalOffset + ",,,yOff[0]:" + yOff[0] + ",,,alpha:1"
//                    )
                    //                            toolbar.getBackground().setAlpha(255);
                    view_titlebar_bg!!.alpha = 1f
                    tv_top_title?.alpha = 1f
                    rlayout_tab.setBackgroundResource(R.color.white)
                    iv_back?.setImageResource(R.drawable.icon_program_home_back_gray)
                    val drawable = Utility.tintDrawable<Drawable>(Color.parseColor("#666666"),
                            ResourcesCompat.getDrawable(resources, R.drawable.icon_program_home_share, null)?.mutate())
                    iv_share?.setImageDrawable(drawable)
                    StatusBarUtil.setLightMode(this@AudioLiveColumnHomeActivity)
                    setEnableRefresh(false)
                } else {
                    rlayout_tab.setBackgroundResource(R.drawable.shape_user_home_tab_bg)
                    val rate = Math.abs(verticalOffset * 1f / yOff[0])
                    //                            toolbar.getBackground().setAlpha((int) (rate * 255));
                    view_titlebar_bg!!.alpha = rate
                    tv_top_title?.alpha = rate
//                    Log.w(
//                            "APPTAG",
//                            "verticalOffset:" + verticalOffset + ",,,yOff[0]:" + yOff[0] + ",,,rate:" + rate
//                    )

                    if (DataUtils.isFloatEquals(rate, 0f)) {
                        iv_back?.setImageResource(R.drawable.icon_program_home_back_white)
                        iv_share?.setImageResource(R.drawable.icon_program_home_share)
                        StatusBarUtil.setDarkMode(this@AudioLiveColumnHomeActivity)
                        setEnableRefresh(true)
                    } else {
                        iv_back?.setImageResource(R.drawable.icon_program_home_back_gray)
                        val drawable = Utility.tintDrawable<Drawable>(Color.parseColor("#666666"),
                                ResourcesCompat.getDrawable(resources, R.drawable.icon_program_home_share, null)?.mutate())
                        iv_share?.setImageDrawable(drawable)
                        StatusBarUtil.setLightMode(this@AudioLiveColumnHomeActivity)
                        setEnableRefresh(false)
                    }
                }
            })
        }
    }

    fun setEnableRefresh(enable: Boolean) {
        mFragments?.forEach {
            if (it is AudioLiveColumnHomeProgrammeListFragment) {
                it.setEnableRefresh(enable)
            } else if (it is AudioLiveColumnHomeRecommendListFragment) {
                it.setEnableRefresh(enable)
            }
        }
    }


    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun getBarTextColorIsDefault(): Boolean {
        return false
    }

    override fun getFitSystemWindow(): Boolean {
        return false
    }

    override fun onClick(v: View) {
        ClickUtils.delayClickable(v)
        when (v.id) {
            R.id.iv_back -> {
                onBackPressed()
            }
            R.id.iv_share -> {
                shareWrap?.show(v)
            }
        }
    }
    protected fun initShare() {
        shareWrap = ShareWrap(this,false)
        shareWrap?.setShowFunction(true)
        shareWrap?.init(programArticleItem,CatalogItem())
//        shareGridDataUtil = SBShareUtils()
//        sharePopGridWindow = SharePopGridWindow(this)
//        sharePopGridWindow?.setShareGirdListener { parent, view, position, id ->
//            if (programArticleItem != null) {
//                ShareGridClickUtil.ShareGridClickHandle(
//                        shareGridDataUtil,
//                        position,
//                        programArticleItem,
//                        CatalogItem(),
//                        this, null
//                )
//            }
//        }
//        shareGridDataUtil?.initBaseShareGridData(this)
//        sharePopGridWindow?.setShareGridAdaptorData(shareGridDataUtil?.BaseShareGridData)

    }
    fun initFragment() {
        viewPager?.visibility = View.VISIBLE
        mTitles.clear()
        mFragments.clear()
        mTitles.add(getString(R.string.program_home_tab_jianjie))
        mFragments.add(AudioLiveColumnHomeIntroFragment.newInstance(getString(R.string.program_home_tab_jianjie), programArticleItem))
        mTitles.add(getString(R.string.program_home_tab_jiemu))
        mFragments.add(AudioLiveColumnHomeProgrammeListFragment.newInstance(getString(R.string.program_home_tab_jiemu), programArticleItem))
        mTitles.add(getString(R.string.program_home_tab_tuijian))
        mFragments.add(AudioLiveColumnHomeRecommendListFragment.newInstance(getString(R.string.program_home_tab_tuijian),
                programArticleItem, programCatalogItem, this))
        mAdapter =
                object : CatalogContentFragmentAdapter(supportFragmentManager, mFragments) {
                    override fun getPageTitle(position: Int): CharSequence? {
                        return mTitles[position]
                    }
                }
        mAdapter?.needDestory = false
        viewPager!!.adapter = mAdapter
        slidingTabLayout!!.setViewPager(viewPager)
        viewPager?.addOnPageChangeListener(onPageChangeListener)
        if (mTitles.size > 1) {
            mCurrentPosition = 1
            viewPager?.currentItem = mCurrentPosition
            viewPager?.post {
                if (mFragments != null && mFragments.size > 0 && mFragments.size > mCurrentPosition) {
                    if (mFragments[mCurrentPosition] is INaviateState) {
                        (mFragments[mCurrentPosition] as INaviateState).choosed()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        viewPager?.removeOnPageChangeListener(onPageChangeListener)

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }


    val onPageChangeListener = object : ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(state: Int) {

        }

        override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
        ) {

        }

        override fun onPageSelected(position: Int) {
            mCurrentPosition = position
            if (mFragments != null && mFragments.size > 0 && mFragments.size > position) {
                if (mFragments[position] is INaviateState) {
                    (mFragments[position] as INaviateState).choosed()
                }
            }
        }

    }


    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt("currentTabPosition", mCurrentPosition)
        super.onSaveInstanceState(outState)
    }

    val compositeDisposable = CompositeDisposable()
    fun getNewsDetail() {
        val map:MutableMap<String,String>  = HashMap()
        map["client"] = "android"
       val d= DataInvokeUtil.getZiMeiTiApi().getArticleById("${programArticleItem?.id ?: ""}",
            map)
                .compose(RxUtils.schedulersTransformer())
                .subscribe({
                    if (isFinishing) {
                        return@subscribe
                    }
                    if (it.body()?.optBoolean("state")==true) {
                        var data: JSONObject? = it.body()?.optJSONObject("data")
                        val meta: JSONObject? = data?.optJSONObject("meta")
                        if (meta != null) {
                            programArticleItem = ArticleItem.parse(meta.toString())
                        }
                        mFragments?.forEachIndexed { index, fragment ->
                            if (fragment is AudioLiveColumnHomeIntroFragment) {
                                fragment.updateUI(programArticleItem)
                                return@forEachIndexed
                            }
                        }
                    }
                }, {
                    if (isFinishing) {
                        return@subscribe
                    }
                }, {

                }, {
                    compositeDisposable.add(it)
                })
    }
}